<template>
  <div class="search">
    <Card>
      <Row @keydown.enter.native="handleSearch">
        <Form
          ref="searchForm"
          :model="searchForm"
          inline
          :label-width="70"
          class="search-form"
          @submit.native.prevent
        >
          <Form-item label="场地名称" prop="keyword">
            <Input
              type="text"
              v-model="searchForm.keyword"
              placeholder="请输入场地名称"
              clearable
              style="width: 200px"
            />
          </Form-item>
          <Button
            @click="handleSearch"
            class="search-btn"
            type="primary"
            icon="ios-search"
            >搜索</Button
          >
        </Form>
      </Row>
      <Row class="operation padding-row">
        <Button @click="addYard" type="error">新增场地</Button>
        <Button @click="batchAppointment" type="error">批量设置预约时间</Button>
        <Button @click="batchDel">批量删除</Button>
      </Row>
      <Table
        :loading="loading"
        border
        :columns="columns"
        sortable="custom"
        class="mt_10"
        :data="data"
        ref="table"
        @on-selection-change="changeSelect"
      ></Table>
      <Row type="flex" justify="end" class="mt_10">
        <Page
          :current="searchForm.page"
          :total="total"
          :page-size="searchForm.rows"
          @on-change="changePage"
          @on-page-size-change="changerows"
          :page-size-opts="[10, 20, 50]"
          size="small"
          show-total
          show-elevator
          show-sizer
        ></Page>
      </Row>
    </Card>

    <!-- 线下坐诊时间设置模态框 -->
    <Modal v-model="editFlag" title="线下坐诊时间设置" :width="900">
      <Form ref="editForm" :model="editForm" :rules="rules" :label-width="100">
        <FormItem label="开放未来" prop="daysOpen" style="width: 50%">
          <InputNumber
            v-model="editForm.daysOpen"
            placeholder="请输入大于0的整数"
            style="width: 50%"
          ></InputNumber
          ><span style="margin-left: 10px">天</span>
        </FormItem>
        <FormItem label="开放日期" prop="weeks" required style="width: 100%">
          <span v-for="(i, k) in dateRange" :key="k">
            <span style="padding: 0 10px">{{ i.label }}</span>
            <i-switch
              size="large"
              @on-change="dayChange"
              true-color="#13ce66"
              :true-value="1"
              :false-value="0"
              v-model="i.value"
            >
              <span slot="open">开放</span>
              <span slot="close">关闭</span>
            </i-switch>
          </span>
        </FormItem>
        <FormItem label="开放时段" prop="siteTimes" style="width: 50%">
          <div v-for="(i, k) in times" :key="k">
            <TimePicker
              type="timerange"
              v-model="i.value"
              @on-change="timeChange"
              format="HH:mm"
              placement="bottom-end"
              placeholder="请选择时段"
              :disabled="i.status != 0"
            ></TimePicker>
            <Icon
              type="md-add"
              v-if="k == times.length - 1"
              style="padding: 10px"
              @click="handleAdd"
            />
            <Icon
              type="md-remove"
              v-if="i.status == 0"
              style="padding: 10px"
              @click="handleDel(i, k)"
            />
          </div>
          <Icon
            type="md-add"
            v-if="!times.length"
            style="padding: 10px"
            @click="handleAdd"
          />
        </FormItem>
      </Form>
      <div slot="footer">
        <Button type="text" @click="editFlag = false">取消</Button>
        <Button type="primary" @click="submitForm">提交</Button>
      </div>
    </Modal>

    <Modal v-model="detailFlag" title="场地详情" :width="900" footer-hide>
      <div class="detail-box">
        <Row :gutter="20">
          <Col span="4" style="text-align: right">场地名称</Col>
          <Col span="20">{{ editRow.siteName || "" }}</Col>
        </Row>
        <Row :gutter="20">
          <Col span="4" style="text-align: right">场地地址</Col>
          <Col span="20">{{ editRow.region || "" }}</Col>
        </Row>
        <Row :gutter="20">
          <Col span="4" style="text-align: right">详细地址</Col>
          <Col span="20">{{ editRow.siteAddress || "" }}</Col>
        </Row>
        <Row :gutter="20">
          <Col span="4" style="text-align: right">工作室数量</Col>
          <Col span="20">{{ editRow.numberOfRooms || "" }}</Col>
        </Row>
        <Row :gutter="20">
          <Col span="4" style="text-align: right">场地照片</Col>
          <Col span="20">
            <img :src="editRow.siteCover" style="width: 150px; height: 150px" />
          </Col>
        </Row>
        <Row :gutter="20">
          <Col span="4" style="text-align: right">场地详情</Col>
          <Col span="20"> <div class="box-border" v-html="editRow.siteDetail"></div></Col>
        </Row>
      </div>
    </Modal>
  </div>
</template>

<script>
import * as API_Yard from "@/api/yard.js";

export default {
  name: "yard",
  data() {
    return {
      loading: false, // 加载状态
      searchForm: {
        // 请求参数
        page: 1,
        rows: 10,
        keyword: "", //场地名称
      },
      selectList: [], // 多选数据
      editFlag: false, // 坐诊时间设置弹窗
      editForm: {
        // 坐诊时段表单
        ids: "",
        daysOpen: "", //开放天数
        weeks: "", //开放日期
        siteTimes: [], //开放时段
      },
      dateRange: [
        { value: 1, label: "周一" },
        { value: 1, label: "周二" },
        { value: 1, label: "周三" },
        { value: 1, label: "周四" },
        { value: 1, label: "周五" },
        { value: 1, label: "周六" },
        { value: 1, label: "周日" },
      ],
      times: [{ value: "", label: "", id: "", status: 0 }],
      rules: {
        // 验证规则
        daysOpen: [
          { required: true, message: "请输入开放天数" },
          {
            pattern: /^[0-9]*[1-9][0-9]*$/,
            message: "只能输入大于0的整数",
            trigger: "blur",
          },
        ],
        siteTimes: [{ required: true, message: "请输入开放时段" }],
      },
      columns: [
        // 表头
        { type: "selection", width: 60, align: "center" },
        { title: "序号", width: 80, type: "index" },
        { title: "场地名称", minWidth: 120, key: "siteName" },
        {
          title: "场地封面",
          tooltip: true,
          minWidth: 240,
          align: "center",
          render: (h, params) => {
            return h("img", {
              attrs: { src: params.row.siteCover },
              style: { width: "150px", height: "100px" },
            });
          },
        },
        { title: "场地地址", key: "siteAddress", minWidth: 120, tooltip: true },
        { title: "创建时间", key: "createTime", minWidth: 120, tooltip: true },
        {
          title: "状态",
          minWidth: 130,
          render: (h, params) => {
            return h("div", [
              h("div", {
                style: {
                  display: "inline-block",
                  width: "8px",
                  height: "8px",
                  backgroundColor: params.row.status == 0 ? "#68CABE" : "#FF5C58",
                  marginRight: "6px",
                  borderRadius: "50%",
                },
              }),
              h("span", {}, params.row.status == 0 ? "启用" : "禁用"),
            ]);
          },
        },
        {
          title: "操作",
          align: "center",
          width: 240,
          fixed: "right",
          render: (h, params) => {
            let func = [];
            func.push(this.btnDom(h, "warning", "查看", "handleView", params));
            func.push(this.btnDom(h, "success", "预约时段", "appointment", params));
            func.push(this.btnDom(h, "info", "编辑", "editPerm", params, true));
            let label = params.row.status == 0 ? "禁用" : "启用";
            func.push(this.btnDom(h, null, label, "handleStatus", params));
            return h(
              "div",
              { style: { display: "flex", justifyContent: "center" } },
              func
            );
          },
        },
      ],
      data: [], // 表单数据
      total: 0, // 表单数据总数
      editRow: {}, //单选数据
      detailFlag: false, // 详情弹窗
    };
  },
  methods: {
    // 分页 改变页码
    changePage(v) {
      this.searchForm.page = v;
      this.getData();
    },
    // 分页 改变页数
    changerows(v) {
      this.searchForm.rows = v;
      this.searchForm.page = 1;
      this.getData();
    },
    // 按钮
    btnDom(h, type = null, label = "", method, params, ghost = false) {
      return h(
        "Button",
        {
          props: { type, size: "small", ghost },
          style: { marginRight: "5px" },
          on: {
            click: () => {
              this[method](params.row, label);
            },
          },
        },
        label
      );
    },
    // 搜索
    handleSearch() {
      this.searchForm.page = 1;
      this.searchForm.rows = 10;
      this.getData();
    },
    //修改
    editPerm(v) {
      this.$router.push({
        name: "yard-form",
        query: { id: v.id },
      });
    },
    // 查看
    handleView(v) {
      API_Yard.getYardDetail(v.id).then((res) => {
        if (res.success) {
          this.editRow = res.result;
          this.detailFlag = true;
        }
      });
    },
    // 新增
    addYard() {
      this.$router.push({
        name: "yard-form",
        query: { id: null },
      });
    },
    // 新增开放时段
    handleAdd() {
      this.times.push({ value: "", label: "", id: "", status: 0 });
      this.timeChange();
    },
    // 删除开放时段
    handleDel(row, index) {
      if (row.id) {
        this.$Modal.confirm({
          title: "确认删除",
          content: "<p>您确认要删除时段【" + row.value.join("~") + "】吗？</p>",
          onOk: () => {
            API_Yard.delYardTime(row.id).then((res) => {
              if (res.success) {
                this.$Message.success("删除成功");
                this.times.splice(index, 1);
                this.timeChange();
              }
            });
          },
        });
      } else {
        this.times.splice(index, 1);
        this.timeChange();
      }
    },
    //多选
    changeSelect(e) {
      this.selectList = e;
    },
    // 设置坐诊时段
    appointment(row) {
      // 回显开放天数
      this.editForm = {
        daysOpen: row.daysOpen,
        weeks: row.weeks,
        siteTimes: [], //开放时段
      };
      // 回显开放日期
      let weeks = row.weeks.split("");
      this.dateRange.forEach((i, k) => {
        i.value = parseInt(weeks[k]);
      });
      API_Yard.getYardTime(row.id).then((res) => {
        if (res.success) {
          if (res.result && res.result.length) {
            // 回显时段
            this.times = res.result.map((i) => {
              return {
                value: i.timeSlot.split("~"),
                label: "",
                id: i.id,
                status: i.status,
              };
            });
            this.editForm.siteTimes = res.result.map((i) => {
              return { timeSlot: i.timeSlot, id: i.id, status: i.status };
            });
          } else {
            this.times = [];
            this.handleAdd();
          }
          this.editRow = row;
          this.editFlag = true;
          this.$refs.table.selectAll(false);
        }
      });
    },
    // 批量坐诊时段
    batchAppointment() {
      if (this.selectList.length) {
        this.editFlag = true;
        this.editRow = {};
        this.editForm = {
          ids: "",
          daysOpen: "",
          weeks: "",
          siteTimes: [],
        };
        this.dayChange();
      } else {
        this.$Message.warning("请先勾选数据");
      }
    },
    // 批量删除
    batchDel() {
      if (this.selectList.length) {
        this.$Modal.confirm({
          title: "确认删除",
          content: "<p>您确认要删除所选的" + this.selectList.length + "条数据？</p>",
          onOk: () => {
            let ids = this.selectList
              .map((i) => {
                return i.id;
              })
              .join(",");
            API_Yard.delYard(ids).then((res) => {
              if (res.success) {
                this.$Message.success("删除成功");
                this.getData();
              }
            });
          },
        });
      } else {
        this.$Message.warning("请先勾选数据");
      }
    },
    // 选择开放日期
    dayChange() {
      this.editForm.weeks = this.dateRange
        .map((i) => {
          return i.value;
        })
        .join("");
    },
    // 选择开放时段
    timeChange() {
      let temp = this.times.filter((i) => i.value);
      this.editForm.siteTimes = temp.map((i) => {
        return {
          timeSlot: i.value.join("~"),
          id: i.id,
          status: i.status,
          siteId: this.selectList.length ? null : this.editRow.id,
        };
      });
    },
    // 提交设置
    submitForm() {
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          if (this.selectList.length) {
            // 批量提交
            this.editForm.ids = this.selectList.map((i) => {
              return i.id;
            });
          } else {
            this.editForm.ids = [this.editRow.id];
          }
          API_Yard.postYardTime(this.editForm).then((res) => {
            if (res.success) {
              this.$Message.success("修改成功！");
              this.editFlag = false;
              this.resetTime();
              this.getData();
            }
          });
        }
      });
    },
    resetTime() {
      this.editForm = {
        // 坐诊时段表单
        ids: "",
        daysOpen: "", //开放天数
        weeks: "", //开放日期
        siteTimes: [], //开放时段
      };
      this.dateRange = [
        { value: 1, label: "周一" },
        { value: 1, label: "周二" },
        { value: 1, label: "周三" },
        { value: 1, label: "周四" },
        { value: 1, label: "周五" },
        { value: 1, label: "周六" },
        { value: 1, label: "周日" },
      ];
      this.times = [{ value: "", label: "" }];
    },
    //查询场地列表
    getData() {
      this.loading = false;
      API_Yard.postYardPage(this.searchForm)
        .then((res) => {
          if (res.result.rows) {
            this.data = res.result.rows;
            this.total = parseInt(res.result.total);
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 禁-启用状态
    handleStatus(v) {
      let params = {
        siteId: v.id,
        type: v.status == 0 ? 1 : 0,
      };
      this.$Modal.confirm({
        title: "确认" + (v.status == 0 ? "禁用" : "启用"),
        content:
          "<p>您确认要" +
          (v.status == 0 ? "禁用" : "启用") +
          "场地【" +
          v.siteName +
          "】？</p>",
        onOk: () => {
          API_Yard.getYardStatus(params).then((res) => {
            if (res.success) {
              this.$Message.success((v.status == 0 ? "禁用" : "启用") + "成功");
              this.getData();
            }
          });
        },
      });
    },
  },
  mounted() {
    this.getData();
  },
};
</script>
<style lang="scss" scoped>
::v-deep .ivu-table-wrapper {
  width: 100%;
}
::v-deep .ivu-card {
  width: 100%;
}
.face {
  width: 60px;
  height: 60px;
  border-radius: 50%;
}
.detail-box {
  width: 100%;
  max-height: 600px;
  overflow-x: hidden;
  overflow-y: auto;
  .ivu-row {
    padding: 10px;
  }
}
</style>
